package net.huashitong.user.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.service.SysTableService;
import net.huashitong.user.dao.RoleDao;
import net.huashitong.user.entity.Department;
import net.huashitong.user.entity.Role;
import net.huashitong.user.filter.RoleFilter;
import net.huashitong.utils.BeanSetGetUtil;
import net.huashitong.utils.CompareUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class RoleService extends StringPKService<Role> {

    @Autowired
    private RoleDao dao;
    @Autowired
    private SysTableService tableService;

    @Override
    protected BaseDao<Role, String> getDao() {
        return dao;
    }
    @Override
    protected void beforeSave(Role obj) {
        obj.setSysId(tableService.updateMaxSysId("t_bnp_role", null));
    }


    public List<Role> queryByFilter(RoleFilter filter){
        return dao.queryByFilter(filter);
    }

    public List<Role> queryByFilterNoPage(RoleFilter filter){
        return  dao.queryByFilterNoPage(filter);
    }

    public void addRole(RoleFilter filter){
        Role role = new Role();
        BeanUtils.copyProperties(filter, role);
//        role = dealWithTypeName(role);
        this.save(role);
    }

    public void updateRole(Role oldRole,Role newRole) throws NoSuchFieldException {
        //**********修改方法*********
        String[] arrays = {
                "updUser",
                "updTime",
                "updDate",
                "createUser",
                "createTime",
                "createDate"
        };
//        newDept = dealWithTypeName(newDept);
        Map<String, List<Object>> map = CompareUtil.compareFields(oldRole, newRole, arrays);
        Iterator<Map.Entry<String, List<Object>>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<Object>> entry = entries.next();
            String key = entry.getKey();
            List<Object> value = entry.getValue();
            BeanSetGetUtil.setValue(oldRole,
                    oldRole.getClass(),
                    key,
                    Role.class.getDeclaredField(key).getType(),
                    value.get(1));
        }
        //**********修改方法*********
        this.update(oldRole);
    }

    public boolean queryRoleExist(String roleName){
        List<Role> list = dao.queryRoleExist(roleName);
        if (list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
